package com.lzy.concertticket.service.impl;

import com.lzy.concertticket.service.FileService;
import com.lzy.concertticket.util.ResourceUtil;
import com.lzy.concertticket.util.UrlUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

import static com.lzy.concertticket.util.ResourceUtil.getFileSourceCodeRootPath;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private UrlUtil urlUtil;

    @Autowired
    private ExecutorService executorService;

    @Override
    public String uploadImage(MultipartFile multipartFile) {
        try {
            //  获取文件输入流
            BufferedInputStream fis = new BufferedInputStream(multipartFile.getInputStream());
            //  通过uuid生成唯一文件名
            String fileName = UUID.randomUUID().toString() + "_" + multipartFile.getOriginalFilename();
            String filePath = ResourceUtil.getImageRootPath() + fileName;
            //  创建文件以及输出流
            FileOutputStream fos = new FileOutputStream(filePath);
            //  创建缓冲区
            byte[] buffer = new byte[1024];
            while (true){
                int len = fis.read(buffer);
                if (len == -1) {
                    break;
                }
                fos.write(buffer, 0, len);
                fos.flush();
            }
            fis.close();
            fos.close();
            //  异步同步文件到源代码目录
            executorService.submit(() -> {
                String originalFilePath = filePath;
                //  计算备份文件名
                String backupFileName = ResourceUtil.getImageSourceCodeRootPath() + fileName;

                try {
                    //  创建输出流
                    FileOutputStream fosBackup = new FileOutputStream(backupFileName);
                    //  获取输入流
                    FileInputStream fisOrigin = new FileInputStream(originalFilePath);

                    //  创建缓冲区
                    while (true){
                        int len = fisOrigin.read(buffer);
                        if (len == -1) {
                            break;
                        }
                        fosBackup.write(buffer, 0, len);
                        fosBackup.flush();
                    }

                    fosBackup.close();
                    fisOrigin.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
            return urlUtil.getResourceImageUrlPath(fileName);
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
